package cn.xmallmanager.services.impl;

import cn.xmallmanager.commons.models.ItemStatus;
import cn.xmallmanager.commons.models.PageQueryResult;
import cn.xmallmanager.dao.ItemMapper;
import cn.xmallmanager.models.Item;
import cn.xmallmanager.models.ItemExample;
import cn.xmallmanager.services.ItemService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

/**
 * Created by MoTaiXian on 2017/7/11.
 */
@Service
public class ItemserviceImpl implements ItemService {
    private static final Logger logger = LoggerFactory.getLogger(ItemserviceImpl.class);

    @Autowired
    private ItemMapper itemMapper;

    @Override
    @Transactional(propagation= Propagation.REQUIRED)
    public void save(Item item) {
        itemMapper.insert(item);
    }

    @Override
    public Item getById(long id) {
        ItemExample itemExample= new ItemExample();
        ItemExample.Criteria criteria=itemExample.createCriteria();
        criteria.andIdEqualTo(id);
        List<Item> rst_list=itemMapper.selectByExample(itemExample);

        if(rst_list!=null && rst_list.size()>0){
            return rst_list.get(0);
        }

        return null;
    }

    @Override
    @Transactional(propagation= Propagation.REQUIRED)
    public void deleteById(long id) {
        ItemExample itemExample= new ItemExample();
        ItemExample.Criteria criteria=itemExample.createCriteria();
        criteria.andIdEqualTo(id);
        itemMapper.deleteByExample(itemExample);
    }

    @Override
    @Transactional(propagation= Propagation.REQUIRED)
    public void updateStatuByID(long id, ItemStatus status) {
        ItemExample itemExample= new ItemExample();
        ItemExample.Criteria criteria=itemExample.createCriteria();
        criteria.andIdEqualTo(id);
        Item update_Recode=new Item();
        update_Recode.setStatus(status.getCode());
        itemMapper.updateByExampleSelective(update_Recode,itemExample);
    }

    @Override
    public PageQueryResult<Item> getItemsByPage(int page, int records) {
        PageQueryResult<Item> result=new PageQueryResult<>();
        ItemExample itemExample=new ItemExample();
        ItemExample.Criteria criteria=itemExample.createCriteria();
        PageHelper.startPage(page,records);
        List<Item> query_list=itemMapper.selectByExample(itemExample);
        result.setRows(query_list);
        PageInfo<Item> pageInfo = new PageInfo<>(query_list);
        result.setTotal(pageInfo.getTotal());
        return result;
    }

}
